package com.heima.wemedia.config;

import com.alibaba.fastjson.JSONObject;
import com.heima.common.constants.WmNewsConstants;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CachePreloader {

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WmChannelMapper wmChannelMapper;

    @PostConstruct
    public void preloadCache() {
        // 执行缓存预热业务...
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词
        SensitiveWordUtil.initMap(collect);
        redisTemplate.opsForValue().set(WmNewsConstants.SENSITIVE_KEY, JSONObject.toJSONString(collect));
        //缓存频道00
        List<WmChannel> channels = wmChannelMapper.selectList(null);
        redisTemplate.opsForValue().set(WmNewsConstants.CHANNEL_KEY, channels);
    }
}